import { reactive, defineModel } from "vue";
import { message } from "ant-design-vue";
// api
import { uploadImage } from "@/api";
// file
import { base64ToFile, fileToBase64 } from "@/utils";
export function useIndex(params) {
    const useState = reactive({
        imageUrl: params.initConfig?.defaultImage || '',
        fileName: "",
        fileList: [],
        loading: false
    })
  
    /**
     * 上传之前
     */
    const useBeforeUpload = (file) => {
        const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
        if (!isJpgOrPng) {
            message.error("You can only upload JPG file!");
        }
        const isLt2M = file.size / 1024 / 1024 < params.initConfig?.size;
        if (!isLt2M) {
            message.error(`上传的文件不能大于${params.initConfig?.size}M`);
        }
        return isJpgOrPng && isLt2M;
    };

    /**
     * 自定义上传
     */
    const useCustomRequest = (options) => {
        // 是否需要裁切图片
        if (params.initConfig.cropper) {
            // 文件名称
            useState.fileName = options.file.name
            // 文件转换
            fileToBase64(options.file).then(res => params?.cropperRef?.value.edit(res))
            return;
        }
        // 直接上传
        startUploadImage(options.file);
    };

    /**
     * 裁切组件确认回调
     */
    const useConfirmCropper = (baseFile) => {
        const file = base64ToFile(baseFile, useState.fileName);
        useStartUploadImage(file);
    };

    /**
     * 开始上传
     */
    const useStartUploadImage = (file) => {
        // 外部传入的方法
        if (params?.initConfig?.beforeChange) {
            params?.initConfig?.beforeChange(file).then((url) => {
                useOnSuccess({ url })
            }).catch(() => {
                useState.loading = false;
            })
            return
        }
        // 直接上传, 创建form表单
        const form = new FormData();
        form.append("files", file);
        useState.loading = true;
        uploadImage(form)
            .then((res) => {
                const url = res.content.files_path;
                useOnSuccess({ file, url })
            })
            .catch(() => {
                useState.loading = false
            });
    };

    /**
     * 上传成功回调
     */
    const useOnSuccess = (data) => {
        useState.imageUrl = data.url
        useState.loading = false
        // 双向绑定
        params.modelValue.value = data.url;
        // 判断是否有成功回调
        params?.initConfig.onSuccess && params?.initConfig.onSuccess(data);
    }
    
    /**
     * 删除文件
     */
    const useDelete = () => {
        useState.imageUrl = url
        // 双向绑定
        params.modelValue.value = url;
        // 判断是否有成功回调
        params?.initConfig?.onRemove && params?.initConfig?.onRemove();
    };

    return {
        useState,
        useBeforeUpload,
        useCustomRequest,
        useConfirmCropper,
        useDelete
    }
}